package com.example.smartmedicalsystem.service;

import com.example.smartmedicalsystem.entity.Comment;
import com.example.smartmedicalsystem.entity.User;
import com.example.smartmedicalsystem.repository.CommentRepository;
import com.example.smartmedicalsystem.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CommentService {
    private final CommentRepository commentRepository;
    private final UserRepository userRepository;

    @Transactional
    public Comment createComment(Long userId, String content) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Comment comment = new Comment();
        comment.setUser(user);
        comment.setContent(content);
        return commentRepository.save(comment);
    }

    @Transactional
    public Comment replyComment(Long commentId, String reply) {
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("留言不存在"));
        comment.setReply(reply);
        return commentRepository.save(comment);
    }

    public List<Comment> getCommentsByUser(Long userId) {
        return commentRepository.findAllByOrderByCreatedAtDesc();
    }

    public List<Comment> getAllComments() {
        return commentRepository.findAll();
    }
}